package logic

import (
	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/x/errors"
	"microdemo/restful/bff/internal/types"
)

type JwtLogic struct {
}

func NewJwtLogic() *JwtLogic {
	return &JwtLogic{}
}

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
func (l *JwtLogic) GetToken(secretKey string, iat, seconds int64, payload string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	// 可以是用户ID、用户名、过期时间等信息
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func (l *JwtLogic) CheckUserInfo(req *types.LoginRequest) error {
	// 模拟运行时 panic
	if req.Username == "panic" {
		panic(any(errors.New(types.Panic_Error.Code, types.Panic_Error.Msg)))
	}
	// 模拟登录逻辑
	if req.Username != "steven" || req.Password != "123456" {
		// Login_Error 自定义登录业务异常
		return errors.New(types.Login_Error.Code, types.Login_Error.Msg)
	}
	return nil
}
